package com.king.zxing.app.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.king.zxing.app.domain.User;
import com.king.zxing.app.utils.DBSqlLiteHelper;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class UserDao {
    DBSqlLiteHelper myHelper;
    SQLiteDatabase db;

    static private final String TABLE_NAME = "Users";

    public UserDao(Context context) {
        this.myHelper = new DBSqlLiteHelper(context);
        try {
            this.db = this.myHelper.getWritableDatabase();
        } catch (Exception e) {
            this.db = this.myHelper.getReadableDatabase();
        }
        //表创建(判断表是否存在)
        String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (  \n" +
                "    ID INTEGER PRIMARY KEY AUTOINCREMENT,        -- 用户ID（系统生成）\n" +
                "    Username TEXT NOT NULL UNIQUE,               -- 用户名\n" +
                "    PhoneNumber TEXT NOT NULL,                   -- 手机号\n" +
                "    UserPassword TEXT NOT NULL,                  -- 密码（通常建议存储哈希值而不是明文密码）\n" +
                "    Points INTEGER DEFAULT 1000,                 -- 积分\n" +
                "    AvatarID INTEGER DEFAULT 0,                            -- 头像\n" +
                "    LastSignInTime INTEGER,  -- 上次签到时间（毫秒数）\n" +
                "    ConsecutiveSignInCount INTEGER DEFAULT 1      -- 连续签到次数  \n" +
                ");";
        try {
            this.db.execSQL(sql);
        } catch (Exception e) {
            Log.e("user表创建异常", e.toString());
        }

        // 创建默认用户
        String defaultUsername = "admin";
        String defaultPassword = "aaa111";
        try {
            User defaultUser = queryUserByUsernameAndPassword(defaultUsername, defaultPassword);
            if (defaultUser == null) {
                long ignored = addUserForRegister(defaultUsername, "110", defaultPassword);
            }
        } catch (Exception ignored) {
        }
    }

    public long addUserForRegister(String Username, String PhoneNumber, String UserPassword) {
        if (db.isReadOnly()) return -1;
        ContentValues values = new ContentValues();
        values.put("Username", Username);
        values.put("PhoneNumber", PhoneNumber);
        values.put("UserPassword", UserPassword);
        values.put("LastSignInTime", (new Date()).getTime());
        return this.db.insert(TABLE_NAME, null, values);
    }

    static private final String[] Args = new String[]{
            "ID", "Username", "PhoneNumber", "UserPassword", "Points",
            "AvatarID", "LastSignInTime", "ConsecutiveSignInCount"
    };

    public User queryUserByUsernameAndPassword(String username, String userPassword) {
        User userItem = null;
        Cursor cursor = db.query(TABLE_NAME, null,
                "Username=? AND UserPassword=?", new String[]{username, userPassword},
                null, null, null);
        while (cursor.moveToNext()) {
            List<Integer> ptr = new ArrayList<>();
            for (String item : Args) ptr.add(cursor.getColumnIndex(item));
            long ID = cursor.getLong(ptr.get(0));
            String Username = cursor.getString(ptr.get(1));
            String PhoneNumber = cursor.getString(ptr.get(2));
            String UserPassword = cursor.getString(ptr.get(3));
            long Points = cursor.getLong(ptr.get(4));
            long AvatarID = cursor.getLong(ptr.get(5));
            long LastSignInTime = cursor.getLong(ptr.get(6));
            int ConsecutiveSignInCount = cursor.getInt(ptr.get(7));
            userItem = new User(ID, Username, PhoneNumber, UserPassword, Points, AvatarID, LastSignInTime, ConsecutiveSignInCount);
        }
        cursor.close();
        return userItem;
    }

    public void SubPointsByUserID(long ID, int subPointsNumber) {
        Cursor cursor = db.query(TABLE_NAME, null,
                "ID=?", new String[]{String.valueOf(ID)},
                null, null, null);
        cursor.moveToFirst();
        int ptr = cursor.getColumnIndex("Points");
        long Points = cursor.getLong(ptr);
        Log.e("cloyir", "Points:" + Points);
        cursor.close();

        long newPoints = Points - subPointsNumber;
        ContentValues content = new ContentValues();
        content.put("Points", newPoints);
        db.update(TABLE_NAME, content, "ID=?", new String[]{String.valueOf(ID)});
    }

    public String getPointsByUserID(long ID) {
        Cursor cursor = db.query(TABLE_NAME, null,
                "ID=?", new String[]{String.valueOf(ID)},
                null, null, null);
        cursor.moveToFirst();
        int ptr = cursor.getColumnIndex("Points");
        long Points = cursor.getLong(ptr);
        cursor.close();

        return String.valueOf(Points);
    }
}